package com.yuqian.JavaSe.thread.cands;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class SExectorThreadPool {
	public static void main(String[] args) throws InterruptedException {
		// 创建一个固定大小为10 的线程池
		//ExecutorService es = Executors.newFixedThreadPool(10);
		Test test =new Test();
		TestThread t1 =new TestThread(test,"t1");
		TestThread t2 =new TestThread(test,"t2");
		t1.start();
		t2.start();
		
		//Thread.currentThread().join();
		Thread.sleep(100);
		
		t1.interrupt();
		t2.interrupt();
	}

}

class TestThread extends Thread{
	private Test test;
	
	TestThread(Test test,String name){
		super(name);
		this.test = test;
	}
	
	@Override
	public void run() {
		//int i=0;
		while(!isInterrupted()) {
			 //System.out.println(getName() + "执行了" + ++i + "次");  
	         test.print();
		}
	}
}


class Test{
	public synchronized void print() {
		int i=1;
		for(;i<10000;) {
			System.out.println(Thread.currentThread().getName()+"---"+ i);
			if(i%10==0) {
				Thread.yield();  
			}
			i++;
		}
	}
}

class MyLock implements Lock {
	
	//允许两个线程获得锁
	private static Sync syn = new Sync(2);

	static class Sync extends AbstractQueuedSynchronizer {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1286748264789L;

		Sync(int state) {
			setState(state);
		}

		@Override
		public int tryAcquireShared(int reduceCount) {
			for (;;) {
				int current = getState();
				int newCount = current - reduceCount;
				if (newCount < 0 || compareAndSetState(current, newCount)) {
					return newCount;
				}
			}
		}

		@Override
		public boolean tryReleaseShared(int returnCount) {
			for (;;) {
				int current = getState();
				int newCount = current + returnCount;
				if (compareAndSetState(current, newCount)) {
					return true;
				}
			}
		}

	}

	public void lock() {
		// TODO Auto-generated method stub
		syn.acquire(1);

	}

	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub
		syn.acquireSharedInterruptibly(1);

	}

	public boolean tryLock() {
		// TODO Auto-generated method stub
		return syn.tryAcquireShared(1)>=0;
	}

	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	public void unlock() {
		// TODO Auto-generated method stub

	}

	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}